{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab81d910-8e91-4e87-b50d-9919bc39ce0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "# 设置随机数种子以便结果可复现\n",
    "torch.manual_seed(0)\n",
    "\n",
    "# 创建一些随机输入和输出数据\n",
    "input_size = 10\n",
    "output_size = 1\n",
    "batch_size = 5\n",
    "\n",
    "# 随机生成数据\n",
    "x = torch.randn(batch_size, input_size)\n",
    "y = torch.randn(batch_size, output_size)\n",
    "class SimpleModel(nn.Module):\n",
    "    def __init__(self, input_dim, output_dim):\n",
    "        super(SimpleModel, self).__init__()\n",
    "        self.linear = nn.Linear(input_dim, output_dim)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.linear(x)\n",
    "\n",
    "\n",
    "model = SimpleModel(input_size, output_size)\n",
    "criterion = nn.MSELoss()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)\n",
    "epochs = 100\n",
    "\n",
    "for epoch in range(epochs):\n",
    "    # 前向传播\n",
    "    outputs = model(x)\n",
    "    loss = criterion(outputs, y)\n",
    "\n",
    "    # 反向传播和优化\n",
    "    optimizer.zero_grad()\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "\n",
    "    if (epoch+1) % 10 == 0:\n",
    "        print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')\n",
    "new_data_point = torch.randn(1, input_size)\n",
    "prediction = model(new_data_point)\n",
    "print(f'Prediction for new data point: {prediction.item()}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.9",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}